<template>
  <div class="overflow-auto h-[100%]" v-loading="loading">
    <VForm
      class="freight-form"
      ref="form"
      :model="model"
      :fieldList="fieldList"
      :options="formOption"
      :rules="rules"
      :disabled="disabled"
      :originOption="{ ...optionsData, ...options }"
    >
      <template #platform="{ input, value }">
        <PlatformSelect
          @update:model-value="input"
          :model-value="value"
          @change="handleChangePlatform"
        />
      </template>
      <template #shop="{ input, value }">
        <SitesSelect
          @update:model-value="input"
          :model-value="value"
          :platform="platformId"
        />
      </template>
      <template #volume="{ input, value }">
        <Volume @input="input" :value="value" />
      </template>
      <template #warehouse="{ input, value }">
        <WarehouseSelect @update:model-value="input" :model-value="value" />
      </template>
    </VForm>
    <div>
      <el-button :loading="loading" type="primary" @click="handleSubmit">
        计算
      </el-button>
      <el-button :loading="loading" @click="handleReset">重置</el-button>
    </div>
    <div
      class="text-[12px] text-[#333] leading-[22px] bg-[#fafafa] rounded-[8px] px-[8px] py-[8px] mt-[16px]"
    >
      <p class="text-[14px] font-[600]">说明</p>
      <p v-for="item in tips" :key="item">{{ item }}</p>
    </div>
  </div>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import VForm from "@/components/Form/index.vue";
import WarehouseSelect from "@/components/WarehouseSelect/index.vue";
import PlatformSelect from "@/components/PlatformSelect/index.vue";
import SitesSelect from "@/components/SitesSelect/index.vue";
import Volume from "@/components/Volume/index.vue";
import { objectToArray } from "../hooks/index.js";
import { sellingPrice } from "../api";
import { getSkuDetails } from "@/api/crossSys.js";
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  options: { type: Object, default: () => ({}) },
});

const tips = [
  `1、品类佣金如果不填写就会默认为0计算；`,
  `2、成交费:根据站点匹配：美澳：0.3（当地币种）；欧洲：0.35（当地币种）`,
  `3、广告费如果不填写就会默认为0计算；`,
  `4、利润率如果不填写就会默认为0计算；`,
  `5、退款率如果不填写就会默认为0计算；`,
  `6、其他费用如果不填写就会默认为0计算；`,
  `7、国际销售费用如果不填写就会默认为0计算；`,
  `8、打包费如果不填写就会默认为0计算；`,
];

const emit = defineEmits(["update:modelValue", "refresh", "close"]);

const formOption = {
  inline: true,
  labelPosition: "top",
};

const rules = {
  platform_id: [{ required: true, message: "请选择平台", trigger: "blur" }],
  shop: [{ required: true, message: "请选择店铺/平台", trigger: "blur" }],
  // warehouse: [{ required: true, message: "请选择发货仓库", trigger: "blur" }],
  destination_country: [
    { required: true, message: "请选择目的国家", trigger: "blur" },
  ],
};

const form = ref();
const model = ref({});
const loading = ref();
const optionsData = ref({});
const platformId = ref("");


const handleSku = async (val) => {
  if(!val) return;
  const data = await getSkuDetails({sku:val});
  let formValues = form.value.getFormValues();
  let _volume = objectToArray(data?.product_size_cm || {});
  model.value = Object.assign({}, formValues, {
    volume: _volume,
    package_weight: data?.packing_weight_g || null,
    product_cost:Number(data?.purchase_price) || null,
  });
};

const publicStyle = { style: { width: "235px" } };
const fieldList = [
  {
    field: "sku",
    label: "SKU",
    ...publicStyle,
    itemProps: { onChange: handleSku },
  },
  {
    field: "platform_id",
    label: "平台",
    type: "select",
    slot: "platform",
  },
  {
    field: "shop",
    label: "站点/店铺",
    slot: "shop",
  },
  {
    field: "destination_country",
    label: "目的国家",
    type: "select",
    origin: "map.country",
    style: { width: "186px" },
    options: {
      valueKey: "country",
      labelKey: "country_name",
    },
  },
  { field: "warehouse", label: "发货仓库", slot: "warehouse" },
  {
    field: "category_commission_cost",
    label: "品类佣金比例",
    append: "%",
    style: { width: "128px" },
  },
  {
    field: "fixed_cost	",
    label: "固定成交费",
    append: "RMB",
    style: { width: "128px" },
  },
  {
    field: "advertising_cost",
    label: "广告费比例",
    append: "%",
    style: { width: "128px" },
  },
  {
    field: "profitability",
    label: "目标利润率",
    append: "%",
    style: { width: "128px" },
  },
  {
    field: "refund_rate",
    label: "退款率",
    append: "%",
    style: { width: "128px" },
  },
  {
    field: "other_fee_cost",
    label: "其他费用比例",
    append: "%",
    style: { width: "128px" },
  },
  {
    field: "international_sales_cost",
    label: "国际销售费用比例",
    append: "%",
    style: { width: "128px" },
  },
  {
    field: "packing_cost",
    label: "打包费",
    append: "RMB",
    style: { width: "178px" },
  },
  {
    field: "package_weight",
    label: "产品包裹重（取sku数据）",
    append: "g",
    style: { width: "178px" },
  },
  { field: "volume", label: "产品尺寸", slot: "volume", ...publicStyle },
  {
    field: "product_cost",
    label: "采购价（取sku数据）",
    append: "RMB",
    ...publicStyle,
  },
  { field: "province", label: "州", ...publicStyle },
  { field: "city", label: "城市", ...publicStyle },
  { field: "zip_code", label: "邮编", ...publicStyle },
];

const handleChangePlatform = async (e) => {
  platformId.value = e;
};

const handleSubmit = async () => {
  try {
    loading.value = true;
    const { volume, shop, ...formInfo } = await form.value.submit();
    const [length, width, height] = volume || [];
    const {
      code,
      data = [],
      message,
    } = await sellingPrice({
      ...formInfo,
      shop_id: shop?.shopId,
      siteId: shop?.siteId,
      length,
      width,
      height,
    });
    if (code !== 200) {
      emit("tableData", []);
      ElMessage.warning(message);
      return;
    }
    emit("tableData", data);
    ElMessage.success("计算成功");
    // handleClose(true);
  } catch (e) {
    emit("tableData", []);
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleReset = async () => {
  model.value = {};
  await nextTick();
  form.value.resetForm();
  emit("tableData", []);
};
</script>

<style lang="scss" scoped>
.freight-form {
  :deep(.el-form-item) {
    margin-right: 16px;
  }
}
</style>
